package servlet;

import net.sf.json.JSONObject;
import service.CyclingrecordService;
import util.JsonWrapperBuilder;
import util.ResponseUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 骑行记录
 *
 * @author liu
 */
@WebServlet(name = "cyclingRecordServlet", urlPatterns = "/cyclingrecord")
public class CyclingRecordServlet extends HttpServlet {

    private CyclingrecordService cyclingrecordService = new CyclingrecordService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        JSONObject jsonObject = solve(req, resp);
        ResponseUtil.write(resp, jsonObject);
    }

    private JSONObject solve(HttpServletRequest request, HttpServletResponse response) {
        JSONObject result;
        if (allNotNull(request.getParameter("start"), request.getParameter("pagesize"))) {
            int start = Integer.parseInt(request.getParameter("start"));
            int pagesize = Integer.parseInt(request.getParameter("pagesize"));
            int userId = Integer.parseInt(request.getParameter("userId"));
            result = cyclingrecordService.cyclingrecordsPagination(userId, start, pagesize);
        } else if (request.getParameter("cid") != null) {
            result = cyclingrecordService.findByCId(request.getParameter("cid"));
        } else {
            result = failedJSON();
        }
        return result;
    }

    private JSONObject failedJSON() {
        return new JsonWrapperBuilder()
            .setStatus(304)
            .setMsg("failed").build();
    }

    private boolean allNotNull(Object... objects) {
        boolean result = true;
        for (Object object : objects) {
            result = result && (object != null);
        }
        return result;
    }
}
